'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

interface Comment {
  id: number
  postId: number
  author: string
  content: string
  date: string
}

interface CommentsProps {
  postId: number
  initialComments: Comment[]
}

export default function Comments({ postId, initialComments }: CommentsProps) {
  const [comments, setComments] = useState<Comment[]>(initialComments)
  const [author, setAuthor] = useState('')
  const [content, setContent] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!author.trim() || !content.trim()) return

    setIsSubmitting(true)
    try {
      const response = await fetch('/api/comments', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          postId,
          author: author.trim(),
          content: content.trim(),
        }),
      })

      if (!response.ok) throw new Error('提交失败')

      const newComment = await response.json()
      setComments(prev => [...prev, newComment])
      setAuthor('')
      setContent('')
      router.refresh()
    } catch (error) {
      console.error('提交评论失败:', error)
      alert('提交评论失败，请稍后重试')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="mt-12">
      <h2 className="text-2xl font-bold mb-6 dark:text-white">评论</h2>
      
      {/* 评论列表 */}
      <div className="space-y-6 mb-8">
        {comments.length === 0 ? (
          <p className="text-gray-500 dark:text-gray-400">暂无评论，来发表第一条评论吧！</p>
        ) : (
          comments.map(comment => (
            <div key={comment.id} className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="font-medium dark:text-white">{comment.author}</span>
                <time className="text-sm text-gray-500 dark:text-gray-400">
                  {new Date(comment.date).toLocaleString('zh-CN')}
                </time>
              </div>
              <p className="text-gray-700 dark:text-gray-300">{comment.content}</p>
            </div>
          ))
        )}
      </div>

      {/* 评论表单 */}
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="author" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            昵称
          </label>
          <input
            type="text"
            id="author"
            value={author}
            onChange={(e) => setAuthor(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md shadow-sm dark:bg-gray-800 dark:text-white"
            required
            maxLength={50}
          />
        </div>
        <div>
          <label htmlFor="content" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            评论内容
          </label>
          <textarea
            id="content"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            rows={4}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md shadow-sm dark:bg-gray-800 dark:text-white"
            required
            maxLength={500}
          />
        </div>
        <button
          type="submit"
          disabled={isSubmitting}
          className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSubmitting ? '提交中...' : '提交评论'}
        </button>
      </form>
    </div>
  )
} 